<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课时名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入课时名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件名称" prop="videoOriginalName">
        <el-input
          v-model="queryParams.videoOriginalName"
          placeholder="请输入原始文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="试听" prop="isFree">
        <el-select v-model="queryParams.isFree" placeholder="请选择是否收费" clearable>
          <el-option
            v-for="dict in dict.type.edu_video_free"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.edu_video_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeGmtCreate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间">
        <el-date-picker
          v-model="daterangeGmtModified"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['edu:video:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['edu:video:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['edu:video:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['edu:video:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="videoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="课时名称" align="center" prop="title"/>
      <el-table-column label="视频资源" align="center" prop="videoSourceId" show-overflow-tooltip>
        <template slot-scope="scope">
          <router-link :to="'/player/' + scope.row.videoSourceId" class="link-type">
            <span>{{ scope.row.videoSourceId }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="文件名称" align="center" prop="videoOriginalName" show-overflow-tooltip/>
      <el-table-column label="排序" align="center" prop="sort"/>
      <el-table-column label="播放次数" align="center" prop="playCount"/>
      <el-table-column label="试听" align="center" prop="isFree">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.edu_video_free" :value="scope.row.isFree"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.edu_video_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="视频大小(Byte)" align="center" prop="size"/>
      <el-table-column label="创建时间" align="center" prop="gmtCreate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="gmtModified" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtModified, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['edu:video:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['edu:video:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程视频对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课时名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入课时名称"/>
        </el-form-item>
        <el-form-item label="当前视频" prop="videoSourceId">
          <el-input v-model="form.videoSourceId" disabled/>
        </el-form-item>
        <el-form-item label="操作">
          <el-upload
            :on-success="handleVodUploadSuccess"
            :on-remove="handleVodRemove"
            :before-remove="beforeVodRemove"
            :on-exceed="handleUploadExceed"
            :on-progress="handleUploading"
            :action="'http://43.143.114.14/dev-api' + '/vod/upload'"
            :before-upload="getFileInfo"
            :limit="1"
            class="upload-demo"
          >
            <el-button size="small" type="primary">上传视频</el-button>
            <el-tooltip placement="right-end">
              <div slot="content">
                最大支持1G，<br/>
                支持3GP、ASF、AVI、DAT、DV、FLV、F4V、<br/>
                GIF、M2T、M4V、MJ2、MJPEG、MKV、MOV、MP4、<br/>
                MPE、MPG、MPEG、MTS、OGG、QT、RM、RMVB、<br/>
                SWF、TS、VOB、WMV、WEBM 等视频格式上传
              </div>
              <i class="el-icon-question"/>
            </el-tooltip>
          </el-upload>
          <el-button size="small" type="danger" @click="handleVodRemove" v-show="form.videoSourceId !== ''">删除视频</el-button>
        </el-form-item>
        <el-form-item label="文件名称" prop="videoOriginalName">
          <el-input v-model="form.videoOriginalName" disabled/>
        </el-form-item>
        <el-form-item label="视频大小(Byte)" prop="size">
          <el-input v-model="form.size" disabled/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序"/>
        </el-form-item>
        <el-form-item label="试听" prop="isFree">
          <el-select v-model="form.isFree" placeholder="请选择是否收费">
            <el-option
              v-for="dict in dict.type.edu_video_free"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listVideo, getVideo, delVideo, addVideo, updateVideo, deleteVod} from "@/api/edu/video";

export default {
  name: "Video",
  dicts: ['edu_video_status', 'edu_video_free'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程视频表格数据
      videoList: [],
      // 章节id
      chapterId: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 开放试听时间范围
      daterangeGmtCreate: [],
      // 开放试听时间范围
      daterangeGmtModified: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        chapterId: null,
        title: null,
        videoOriginalName: null,
        playCount: null,
        isFree: null,
        status: null,
        gmtCreate: null,
        gmtModified: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          {required: true, message: "课时名称不能为空", trigger: "blur"}
        ],
        sort: [
          {required: true, message: "排序不能为空", trigger: "blur"}
        ],
        isFree: [
          {required: true, message: "开放试听不能为空", trigger: "change"}
        ],
      }
    };
  },
  created() {
    this.chapterId = this.$route.params && this.$route.params.id;
    this.getList();
  },
  methods: {
    /** 查询章节下的视频列表 */
    getList() {
      this.loading = true;
      this.queryParams.chapterId = this.chapterId;
      this.queryParams.params = {};
      if (null != this.daterangeGmtCreate && '' !== this.daterangeGmtCreate) {
        this.queryParams.params["beginGmtCreate"] = this.daterangeGmtCreate[0];
        this.queryParams.params["endGmtCreate"] = this.daterangeGmtCreate[1];
      }
      if (null != this.daterangeGmtModified && '' !== this.daterangeGmtModified) {
        this.queryParams.params["beginGmtModified"] = this.daterangeGmtModified[0];
        this.queryParams.params["endGmtModified"] = this.daterangeGmtModified[1];
      }
      listVideo(this.queryParams).then(response => {
        this.videoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        videoSourceId: null,
        videoOriginalName: null,
        sort: null,
        playCount: null,
        isFree: null,
        duration: null,
        status: null,
        size: null,
        version: null,
        gmtCreate: null,
        gmtModified: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeGmtCreate = [];
      this.daterangeGmtModified = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课程视频";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getVideo(id).then(response => {
        let data = response.data;
        if (data.videoSourceId === undefined) {
          data.videoSourceId = '';
        }
        this.form = data;
        this.form.isFree = String(this.form.isFree)
        this.open = true;
        this.title = "修改课程视频";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.chapterId = this.chapterId;
          if (this.form.id != null) {
            updateVideo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVideo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除？').then(function () {
        return delVideo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('edu/video/export', {
        ...this.queryParams
      }, `video_${new Date().getTime()}.xlsx`)
    },
    //上传视频成功调用的方法
    handleVodUploadSuccess(response, file) {
      //上传视频id赋值
      this.form.videoSourceId = response.msg;
      //上传视频名称赋值
      this.form.videoOriginalName = file.name;
      //关闭加载栏并提示用户
      this.loading = false;
      this.$notify({
        title: '提示',
        message: '视频上传成功! 记得点击确定提交您的修改',
        duration: 0
      });
    },
    handleUploadExceed() {
      this.$message.warning("想要重新上传视频，请先删除已上传的视频");
    },
    // 文件上传时
    handleUploading() {
      this.loading = true
      this.$notify({
        title: '提示',
        message: '服务器努力转码视频中，请稍后...',
        duration: 0
      });
    },
    // 解析上传的文件信息
    getFileInfo(file) {
      //获取视频大小
      this.form.size = file.size
    },
    handleVodRemove() {
      //调用接口的删除视频的方法
      deleteVod(this.form.videoSourceId).then((response) => {
        //提示信息
        this.$message({
          type: "success",
          message: "删除视频成功!",
        });
        //把video视频id和视频名称值清空
        //上传视频id赋值
        this.form.videoSourceId = "";
        //上传视频名称赋值
        this.form.videoOriginalName = "";
      });
    },
    //点击×调用这个方法
    beforeVodRemove(file, form) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
  }
};
</script>
<style lang="css"> .el-tooltip__popper {
  max-width: 30%
} </style>
